<template>
    <el-form :model="form" ref="formRef" label-width="120px" style="padding: 20px;">
        <!-- 表单头部 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="入库单号">
                    <el-input v-model="form.inboundNum[0]" placeholder="可不填写，自动生成"></el-input>
                    <!-- 这里v-model改为form.inboundNum[0]，因为inboundNum是数组类型了 -->
                </el-form-item>
                <el-form-item label="供应商编号" required>
                    <el-input v-model="form.supplierID"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系方式" required>
                    <el-input v-model="form.supplierPhone"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="form.rember" :maxlength="300" placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="入库单类型" prop="storage" required>
                    <el-select v-model.number="form.storage" placeholder="请选择入库类型">
                        <el-option label="原材料入库" value="101"></el-option>
                        <el-option label="成品入库" value="102"></el-option>
                        <el-option label="销售退货入库" value="103"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商名称" prop="supplierName" required>
                    <el-input v-model="form.supplierName"></el-input>
                </el-form-item>
                <el-form-item label="制单人">
                    <el-input v-model="form.creator" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="关联订单号" prop="associatedNum">
                    <el-input v-model="form.associatedNum"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系人" prop="supplierPeople">
                    <el-input v-model="form.supplierPeople"></el-input>
                </el-form-item>
                <el-form-item label="制单时间">
                    <el-input v-model="form.outAuditTime" disabled></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <div>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="centerDialogVisible = true"
                style="float: right; margin-bottom: 10px;">新增产品</el-button>
        </div>
        <!-- 产品表格 -->
        <el-table :data="products" style="margin-top: 20px;" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="产品名称" prop="productName"></el-table-column>
            <el-table-column label="产品编码" prop="productId"></el-table-column>
            <el-table-column label="规格" prop="specification"></el-table-column>
            <el-table-column label="批次">
                <template #default="{ row }">
                    <el-input v-model="row.batch" size="small" placeholder="请输入批次"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="单价">
                <template #default="{ row }">
                    <el-input v-model.number="row.price" size="small" type="number"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="入库数量">
                <template #default="{ row }">
                    <el-input v-model.number="row.quantity" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="总价" width="100">
                <template #default="{ row }">
                    <span :style="row.totalPrice < 0 || isNaN(row.totalPrice) ? 'color: red' : ''">
                        {{ row.totalPrice.toFixed(2) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="库位">
                <template #default="{ row }">
                    <el-select v-model="row.location" size="small" placeholder="请选择库位">
                        <el-option v-for="location in allLocations" :key="location.binlocation"
                            :label="location.binlocation" :value="location.binlocation"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="{ row }">
                    <el-button size="small" icon="el-icon-edit" @click="deleteProduct(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm" style="margin-left: 10px;">取消</el-button>
        </div>
    </el-form>

    <el-dialog v-model="centerDialogVisible" title="选择产品" style="width: 1300px;height: 900px;" center>
        <span>
            <div class="search-container">
                <el-input v-model="from.ProductId" placeholder="请输入产品编号" clearable :disabled="loading" />
                <el-input v-model="from.ProductName" placeholder="请输入产品名称" clearable :disabled="loading" />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="productsData" style="width: 100%;" border row-key="productId" ref="productTableRef">
                <el-table-column type="selection" />
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="productId" label="产品ID"></el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="category" label="类别"></el-table-column>
                <el-table-column prop="specification" label="规格"></el-table-column>
                <el-table-column prop="price" label="单价"></el-table-column>
            </el-table>
            <!-- 新增分页组件 -->
            <el-pagination v-show="from.totalPage > 1" :current-page="from.PageIdex" :page-sizes="[4, 8, 12]"
                :total="from.totalCount" @size-change="handlePageSizeChange" @current-change="handleCurrentChange" />
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addSelectedProducts">添加</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp'

const router = useRouter();
const route = useRoute();
const Store = useCounterStore()

var inboundNum = route.query.inboundNum;
// 表单数据
const form = reactive({
    "pid": 1,
    "inboundNum": [Math.floor(Math.random() * (999 - 100 + 1)) + 100], // 将inboundNum改为数组类型
    "associatedNum": "",
    "quantity": "",
    "storage": 101,
    "supplier": "空",
    "supplierID": "",
    "supplierName": "",
    "supplierPeople": "",
    "supplierPhone": "",
    "creator": Store.user?.userName || '未知用户',
    "reviewer": "空",
    "outAuditTime": new Date().toISOString(),
    "outAuditstatus": 101,
    "outCreationTime": new Date().toISOString(),
    "rember": "",
    "proName": "",
    "proId": "",
    "specifications": "",
    "batch": "",
    "unitprice": "",
    "uNumber": "",
    "price": "",
    "binlocation": "",
    "isDelete": 0,
    "request": "qqqq"
});
// 计算总价
const calculateTotal = (row) => {
    row.price = parseFloat(row.price) || 0;
    row.quantity = parseFloat(row.quantity) || 0;
    row.totalPrice = row.price * row.quantity;
};
// 提交表单
const submitForm = () => {
    // 构建字段数组结构
    const submitData = {
        pid: products.value.map(() => 0), // 根据实际需求填写
        inboundNum: products.value.map(() => String(form.inboundNum)), // 这里也要相应修改为取数组的第一个元素
        associatedNum: products.value.map(() => form.associatedNum),
        quantity: products.value.map(p => String(p.quantity)),
        storage: products.value.map(() => form.storage),
        supplier: products.value.map(() => form.supplier),
        supplierID: products.value.map(() => form.supplierID),
        supplierName: products.value.map(() => form.supplierName),
        supplierPeople: products.value.map(() => form.supplierPeople),
        supplierPhone: products.value.map(() => form.supplierPhone),
        creator: products.value.map(() => form.creator),
        reviewer: products.value.map(() => form.reviewer),
        outAuditTime: products.value.map(() => new Date().toISOString()),
        outAuditstatus: products.value.map(() => form.outAuditstatus),
        outCreationTime: products.value.map(() => new Date().toISOString()),
        rember: products.value.map(() => form.rember),
        proName: products.value.map(p => p.productName),
        proId: products.value.map(p => p.productId),
        specifications: products.value.map(p => p.specification),
        batch: products.value.map(p => p.batch),
        unitprice: products.value.map(p => String(p.price)),
        uNumber: products.value.map(p => String(p.quantity)),
        price: products.value.map(p => String(p.totalPrice)),
        binlocation: products.value.map(p => p.location),
        isDelete: products.value.map(() => 0)
    };


    console.log('提交的数据:', submitData);
    // 提交请求
    KongaUrl.post('wangjunlong1/api/Store/StoreAdd', submitData).then((res) => {
        console.log(submitData.value)
        if (res.data.code === 212) {
            ElMessage.success('提交成功');
            router.push('/StoreShow');
        } else {
            ElMessage.error('提交失败');
        }
    }).catch((error) => {
        if (error.response) {
            ElMessage.error(`提交请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data}`);
        } else if (error.request) {
            ElMessage.error('提交请求已发送，但没有收到响应');
        } else {
            ElMessage.error('提交请求时发生错误: ' + error.message);
        }
        console.error('接口错误：', error);
    });
};

const centerDialogVisible = ref(false);
const from = reactive({
    ProductId: '',
    ProductName: '',
    PageIdex: 1,
    PageSize: 15,
    totalPage: 0,
    totalCount: 0
});

const productsData = ref([]);
const loading = ref(false);
const productTableRef = ref(null);

const Moks = () => {
    loading.value = true;
    KongaUrl("wangjunlong/api/Product/ProductQuser", {
        params: {
            ProductId: from.ProductId,
            ProductName: from.ProductName,
            PageIdex: from.PageIdex,
            PageSize: from.PageSize,
        }
    }).then((res) => {
        productsData.value = res.data.data.list;
        from.totalCount = res.data.data.totalCount;
        from.totalPage = res.data.data.totalPage;
    }).finally(() => {
        loading.value = false;
    });
};

const handlePageSizeChange = (size) => {
    from.PageSize = size;
    from.PageIdex = 1;
    Moks();
};

const handleCurrentChange = (page) => {
    from.PageIdex = page;
    Moks();
};

const handleSearch = () => {
    from.PageIdex = 1;
    Moks();
};

const addSelectedProducts = () => {
    if (!productTableRef.value) {
        ElMessage.error("请先搜索产品");
        return;
    }
    const selectedRows = productTableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
        ElMessage.warning("请至少选择一个产品");
        return;
    }
    const newProducts = selectedRows.map(product => ({
        ...product,
        price: product.price || 0,
        quantity: 0,
        totalPrice: 0,
        batch: '',
        location: ''
    }));
    products.value = [...products.value, ...newProducts];
    centerDialogVisible.value = false;
};

const products = ref([]);
// 取消表单操作
const cancelForm = () => {
    // 重置表单数据
    Object.keys(form).forEach(key => form[key] = '');
    // 清空表格数据
    products.value = [];
};

// 自动生成入库单号
onMounted(() => {
    Moks();
    Warehouseinquiry();
    if (!form.inboundNum[0]) { // 这里也要相应修改为判断数组的第一个元素
        generateInboundNumber();
    }
});

const generateInboundNumber = async () => {
    try {
        const response = await axios.get('/api/inbound-orders/generate-number');
        form.inboundNum[0] = response.data; // 这里也要相应修改为给数组的第一个元素赋值
    } catch (error) {
        ElMessage.error('生成入库单号失败');
    }
};
const deleteProduct = (row) => {
    products.value = products.value.filter(item => item.productId !== row.productId);
    ElMessage.success('产品删除成功');
};
const allLocations = ref([]);
// 仓库查询
const Warehouseinquiry = () => {
    KongaUrl("wangjunlong/api/Store/StoreFile").then((res) => {
        allLocations.value = res.data.data;
    });
};
</script>

<style scoped>
.el-table {
    width: 100%;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.search-container .el-input {
    flex: 1;
    max-width: 200px;
}
</style>